package com.sam.im.sms.index.activitys;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.sam.im.greendao.DaoSession;
import com.sam.im.greendao.NumberEntityDao;
import com.sam.im.sms.R;
import com.sam.im.sms.app.MyApp;
import com.sam.im.sms.base.BaseActivity;
import com.sam.im.sms.entity.NumberEntity;
import com.sam.im.sms.index.adapters.BlackListAdapter;
import com.sam.im.sms.setting.SMSSettingImpl;
import com.sam.im.sms.setting.Setting;
import com.sam.im.sms.util.DataFormat;
import com.sam.im.sms.util.Utils;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
/**
 * 描述
 * liuyucheng
 * Created By 刘育成 on 2019/6/4.
 */
public class BlackListActivity extends BaseActivity implements View.OnClickListener {
    private TextView mTvBack;
    private TextView mTextView;
    private TextView mTvAdd;
    private DaoSession mDaoSession;
    private RecyclerView mRecyclerView;
    private List<NumberEntity> mList;
    private TextView mEmptText;
    private BlackListAdapter mAdapter;
    LinearLayoutManager mLayoutManager;
    private Context mContext;
    //SEP1定义的是*空格，忽动
    private static final String SEP1 = "* ";
    Setting mSetting;


    @Override
    public int getContentViewId() {
        return R.layout.activity_black_list;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        mDaoSession = MyApp.getDaoSession();
        mSetting = SMSSettingImpl.getInstance();
        initViews();

    }

    private void showLogs(List<NumberEntity> entityList) {
        mAdapter.replaceData(entityList);
    }


    private void initViews() {
        mContext = this;
        mTvBack = findViewById(R.id.tv_back);
        mTextView = findViewById(R.id.textView);
        mTvAdd = findViewById(R.id.tv_add);
        mRecyclerView = findViewById(R.id.rec_list);
        mEmptText = findViewById(R.id.empty_text);
        mTvBack.setOnClickListener(this::onClick);
        mTvAdd.setOnClickListener(this::onClick);
        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new BlackListAdapter(mContext);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnViewItemClickListener(new BlackListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int view) {

            }

            @Override
            public void onItemLongClick(int i) {
                new MaterialDialog.Builder(BlackListActivity.this)
                        .title("提示")
                        .content("是否删除该条黑名单")
                        .onNegative(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                            }
                        })
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                NumberEntity numberEntity = mDaoSession.getNumberEntityDao().queryBuilder().where(NumberEntityDao.Properties.Number.eq(mList.get(i).getNumber())).unique();
                                mDaoSession.getNumberEntityDao().delete(numberEntity);
                                Thread thread = new Thread(new MyRunable());
                                thread.start();
                            }
                        })
                        .negativeText("取消")
                        .positiveText("确定").show();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        Thread thread = new Thread(new MyRunable());
        thread.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.tv_add:
                new MaterialDialog.Builder(this)
                        .title(getResources().getString(R.string.hangup_number_keyword))
                        .widgetColor(Color.BLUE)
                        .inputType(InputType.TYPE_CLASS_PHONE)
                        .input(getResources().getString(R.string.hangup_keyword_hint), "", new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                                if (input.length() < 2) {
                                    Toast.makeText(BlackListActivity.this, "号码段最少3位", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                if (!TextUtils.isEmpty(input)) {
                                    List<NumberEntity> list = mDaoSession.getNumberEntityDao().queryBuilder().where(NumberEntityDao.Properties.Number.eq(input)).list();
                                    mDaoSession.getNumberEntityDao().insertOrReplace(new NumberEntity(list.size() == 0 ? null : list.get(0).getId(), input + ""));
                                    Thread thread = new Thread(new MyRunable());
                                    thread.start();
                                }
                            }
                        })
                        .show();
                break;
        }
    }

    private class MyRunable implements Runnable {
        @Override
        public void run() {
            mSetting.remove("isNumberKeyword");
            mList = mDaoSession.getNumberEntityDao().loadAll();
            StringBuffer sb = new StringBuffer();
            if (mList == null || mList.size() == 0) {
                showNoCallLog(true);
            } else {
                showNoCallLog(false);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        for (int x = 0; x < mList.size(); x++) {
                            Log.e("lyc::::::", mList.get(x).getNumber());
                            sb.append(mList.get(x).getNumber());
                            sb.append(SEP1);
                        }
                        mSetting.setNumberKeyword("isNumberKeyword", sb.toString());
                        Log.e("lyc::名单", mSetting.getNumberKeyword("isNumberKeyword"));
                        mAdapter.replaceData(mList);
                    }
                });
            }
        }
    }

    private void showNoCallLog(final boolean show) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mEmptText.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });
    }
}
